<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '选择省市区',
  },
}
</route>

<template>
  <view class="absolute left-0 right-0"
    :style="{ top: '0', bottom: bottom + 'px' }"
  >
    <view class="w-full h-1px"></view>
    <view 
      class="rounded-12rpx w-center m-a bg-#fff !mt-32rpx" 
      style="height: calc(100% - 200rpx);"
      :class="[
        { 'dark-color2': themeConfig.theme === 'dark' },
      ]"
    >
      <view class="font-size-26rpx pt-32rpx pb-20rpx flex-sb-center">
        <text>当前选择</text>
        <text class="color-#9C6DEF" @click="handlePositioning" v-if="isPositioning">
          <wd-loading v-if="positionLoading" color="#9C6DEF" :size="12" />
          <i class="iconfont icon-dingwei inline-block font-size-24rpx mr-6rpx" v-else></i>
          重新定位
        </text>
        <text class="color-#9C6DEF" @click="handleReset" v-else>
          <i class="iconfont icon-dingwei inline-block font-size-24rpx mr-6rpx"></i>
          重新选择
        </text>
      </view>
      <view class="font-size-32rpx font-600 pb-20rpx text-center">
        <text v-for="(item, index) in pickerLabels" :key="index">{{ item === '所有' ? '' : item }}</text>
        <text v-if="!pickerLabels.length">{{ isAll ? cityName : '请选择' }}</text>
      </view>
      <view class="border-1px"></view>

      <view class="flex py-32rpx relative" style="height: calc(100% - 224rpx);">
        <view class="position-center" v-if="common.getRegionInfoLoading && !colPickerData.length">
          <wd-loading color="#9C6DEF" />
        </view>
        <scroll-view 
          class="w-1/3 box-border h-full" 
          :scroll-y="true" 
          :show-scrollbar="false"
          :scroll-top="scrollTopList[0]"
          :scroll-with-animation="true"
        >
          <view class="w-200rpx min-h-30px m-a flex-center leading-28rpx font-size-26rpx rounded-8rpx mb-12px flex-wrap box-border p-6rpx text-center"
            v-for="(item, index) in colPickerData"
            :key="item.id"
            :class="[{ 'selected': pickerValue[0] === item.id }]"
            @click="handleChangePicker(item, index, 0)"
          >{{ item.name }}</view>
        </scroll-view>
        
        <scroll-view 
          class="w-1/3 box-border h-full" 
          :scroll-y="true" 
          :show-scrollbar="false"
          v-if="colPickerData[pickerIndexList[0]]"
          :scroll-top="scrollTopList[1]"
          :scroll-with-animation="true"
        >
          <view class="w-200rpx min-h-30px m-a flex-center leading-28rpx font-size-26rpx rounded-8rpx mb-12px flex-wrap box-border p-6rpx text-center"
            v-for="(item, index) in colPickerData[pickerIndexList[0]].children"
            :key="item.id"
            :class="[{ 'selected': pickerValue[1] === item.id }]"
            @click="handleChangePicker(item, index, 1)"
          >{{ item.name }}</view>
          <view class="border-center"></view>
        </scroll-view>
        
        <scroll-view 
          class="w-1/3 box-border h-full" 
          :scroll-y="true" 
          :show-scrollbar="false"
          v-if="colPickerData[pickerIndexList[0]]?.children[pickerIndexList[1]]"
          :scroll-top="scrollTopList[2]"
          :scroll-with-animation="true"
        >
          <view class="w-200rpx min-h-30px m-a flex-center leading-28rpx font-size-26rpx rounded-8rpx mb-12px flex-wrap box-border p-6rpx text-center"
            v-for="(item, index) in colPickerData[pickerIndexList[0]].children[pickerIndexList[1]].children"
            :key="item.id"
            :class="[{ 'selected': pickerValue[2] === item.id }]"
            @click="handleChangePicker(item, index, 2)"
          >{{ item.name }}</view>
          <view class="border-center"></view>
        </scroll-view>
      </view>
    </view>

    <view class="position-b-center !fixed w-750rpx m-a pt-24rpx bg-#fff box-sd"
      :style="{ paddingBottom: safeAreaInsets.bottom + 'px' }"
      :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
    >
      <view class="btn-full w-center">
        <wd-button 
          class="btn-w-full btn-h-78"
          @click="submit"
        >确定</wd-button>
      </view>
      <view class="pb-24rpx"></view>
    </view>
  </view>
</template>
  
<script lang="ts" setup>
import { Main } from "@/service/types";
import { useCommonStore, useThemeStore } from "@/store";
import { back } from "@/utils";
import { useToast } from "wot-design-uni";

// 主题颜色
const { themeConfig } = useThemeStore();
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
const common = useCommonStore();
const toast = useToast();

const safeTop = safeAreaInsets?.top || 0;
const safeBottom = safeAreaInsets?.bottom || 0;
const top = ref(safeTop);
const bottom = ref(safeBottom);
// #ifdef MP-WEIXIN
top.value = safeTop + 44;
// #endif

// 选择地址相关
const pickerValue = ref([]);
const pickerLabels = ref([]);
const pickerIndexList = ref([]);
const column = ref(3);
const isAll = ref(true); // 是否显示全国
const isRequired = ref('1'); // 1非必填到区, 2必填到区

const colPickerData = ref([]);

// 重新选择
const handleReset = () => {
  if (!isAll.value) {
    pickerValue.value = [];
    pickerIndexList.value = [];
    pickerLabels.value = [];
    return
  }
  pickerValue.value = [''];
  pickerIndexList.value = [0];
  pickerLabels.value = [cityName.value];
}

// 是否显示重新定位
const isPositioning = ref(false);
const positionLoading = ref(false);
const handlePositioning = async() => {
  try {
    positionLoading.value = true;
    // 获取ip地址信息
    await common.getBaiduyunIp2address();
    positionLoading.value = false;
  } catch (error) {
    positionLoading.value = false;
  }
  const { provinceId, cityId, districtId } = common.commonState.addressInfo || {};
  const list = [provinceId, cityId, districtId].filter(item => !!item).map(item => item.toString());
  backfill(list);
}

const submit = () => {
  if (isRequired.value === '2' && pickerValue.value.length < 3) {
    return toast.show('请选择到区');
  }
  const vals = pickerValue.value.join(',');
  const labels = pickerLabels.value.map(item => {
    return item === '所有' ? '' : item;
  }).join(',');
  const data = pickerValue.value.length ? `${vals}/${labels}` : '';
  uni.$emit('updateArea' + pageName.value, data);
  back();
}

const scrollTopList = ref([0, 0, 0]);
// 简单计算滚动高度
const getScrollTop = () => {
  const _scrollTopList = [];
  for (let i = 0; i < column.value; i++) {
    let top = 0;
    if (pickerIndexList.value[i]) {
      top = pickerIndexList.value[i] * 42;
    }
    _scrollTopList.push(top);
  }
  scrollTopList.value = _scrollTopList;
}

// 点击选择
const handleChangePicker = (item: Main.RegionInfo, index, type = 0) => {
  if (type < column.value) {
    const len = type + 1;
    pickerValue.value.length = len;
    pickerLabels.value.length = len;
    pickerIndexList.value.length = len;
  }
  pickerValue.value[type] = item.id;
  pickerIndexList.value[type] = index;
  pickerLabels.value[type] = item.name;
}

// 回填
const backfill = (vals = []) => {
  if (!vals.length) {
    pickerValue.value = ['']
    return
  };

  pickerValue.value = vals;
  const _valueList = [];
  const labelList = [];
  pickerValue.value.forEach((item, index) => {
    let i = undefined;
    if (index === 0) {
      i = colPickerData.value.findIndex(areaItem => {
        if (areaItem.id === item) {
          labelList.push(areaItem.name);
        }
        return areaItem.id === item;
      })
    } else if (index === 1) {
      i = colPickerData.value[_valueList[0]].children.findIndex(areaItem => {
        if (areaItem.id === item) {
          labelList.push(areaItem.name);
        }
        return areaItem.id === item;
      })
    } else if (index === 2) {
      i = colPickerData.value[_valueList[0]].children[_valueList[1]].children.findIndex(areaItem => {
        if (areaItem.id === item) {
          labelList.push(areaItem.name);
        }
        return areaItem.id === item;
      })
    }
    i >= 0 && _valueList.push(i);
  })

  pickerIndexList.value = _valueList;
  pickerLabels.value = labelList;

  setTimeout(() => {
    getScrollTop();
  }, 100)
}

const getPickerData = (vals) => {
  const { colPickerData: _colPickerData } = useColPickerData(isAll.value, cityName.value);
  colPickerData.value = _colPickerData;
  backfill(vals);
}

const pageName = ref('');
const cityName = ref('全国');
onLoad((options) => {
  const { 
    areaStr, 
    isRequired: _isRequired, 
    page, 
    isAll: _isAll,
    type,
    cityName: _cityName,
  } = options || {};

  cityName.value = _cityName || '全国';
  isPositioning.value = type === '1' ? true : false;
  isAll.value = _isAll === '1' ? false : true;
  pageName.value = page || '';
  isRequired.value = _isRequired || '1';
  const vals = areaStr ? areaStr.split(',') : [];

  if (isAll.value) {
    pickerValue.value = [''];
    pickerIndexList.value = [0];
    pickerLabels.value = [cityName.value];
  }

  if (common.hasRegionInfo) {
    if (colPickerData.value.length) {
      return backfill(vals);
    }
    getPickerData(vals);
  } else {
    common.regionInfoCallback.push(getPickerData.bind(null, vals));
  }
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '选择省市区';
  })
})
</script>

<style lang="scss" scoped>
.selected {
  color: #fff;
  background: linear-gradient( 180deg, #9C6DEF 0%, #E5C4FF 100%);
}

.border-center {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translate(0, -50%) scaleX(0.5);
  width: 1px;
  height: calc(100%);
  background-color: rgba(187, 187, 187, 0.6);
}
</style>
        